package com.hy.example.shared.utils;

import com.hy.example.shared.model.ProcessResultDTO;
import com.hy.example.shared.model.ProcessResultDTO;
import com.hy.example.shared.model.ProcessResultDTO;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Slf4j
public class ProcessUtil {

    private ProcessUtil() {
    }

    public static ProcessResultDTO executeCmd(String[] command) throws IOException {
        log.debug("execute cmd:{}", String.join(" ", command));
        Process process = Runtime.getRuntime().exec(command);
        String line;
        StringBuilder outMessage = new StringBuilder();
        StringBuilder errMessage = new StringBuilder();
        try (BufferedReader brOut = new BufferedReader(new InputStreamReader(process.getInputStream()));
             BufferedReader brErr = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
            while ((line = brOut.readLine()) != null) {
                log.debug("out:{}", line);
                outMessage.append(line);
            }
            while ((line = brErr.readLine()) != null) {
                log.error("err:{}", line);
                errMessage.append(line);
            }
            int exitCode = process.waitFor();
            return ProcessResultDTO.builder()
                    .code(exitCode)
                    .errorMsg(errMessage.toString())
                    .outMsg(outMessage.toString())
                    .build();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException(e.getMessage());
        } catch (IOException e) {
            log.error("process failed, exception:{}", e.getMessage());
            throw new IOException(e.getMessage());
        }
    }
}
